package com.qxzn.app.personalcenter.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.FaceDetectionBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.model.LoginAndRegisterModel;
import com.qxzn.app.page.util.PermissionUtil;
import com.qxzn.app.page.view.FaceBgView;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.page.widget.camera.CameraInterface;
import com.qxzn.app.page.widget.camera.CameraPreview;
import com.qxzn.app.page.widget.statusbar.StatusBar;
import com.qxzn.app.personalcenter.R;
import com.qxzn.app.personalcenter.R2;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.FileUtil;
import com.qxzn.app.util.SystemUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import news.jaywei.com.compresslib.CompressTools;

/**
 * 注册6-人脸2
 */
public class RegisterFace2Activity extends BaseActivity implements CameraInterface.CameraListener, MyInterface.OnFaceDetectionListener, MyInterface.AllPermissionGrantListener {

    @BindView(R2.id.fl_camera)
    FrameLayout flCamera;
    @BindView(R2.id.faceView)
    FaceBgView faceView;
    private CameraPreview mSurfaceView;
    private LoginAndRegisterModel loginAndRegisterModel;
    private File file1;
    private boolean result;

    @Override
    protected int initLayout() {
        return R.layout.activity_register_face2;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void iniTitleBar() {
        StatusBar.translucentStatusBar(this);
        title_bar.setVisibility(View.GONE);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        result = getIntent().getBooleanExtra("result", false);
        loginAndRegisterModel = new LoginAndRegisterModel(this);
        loginAndRegisterModel.setOnFaceDetectionListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needRequestPermission) {
            needRequestPermission = false;
            requestPermission(this, PermissionUtil.READ_EXTERNAL_STORAGE, PermissionUtil.WRITE_EXTERNAL_STORAGE, PermissionUtil.CAMERA);
        }
    }

    @Override
    protected void setFullScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 初始化相机
     */
    private void initCameraView() {
        CameraInterface.getInstance().setmCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT);
        CameraInterface.getInstance().setCameraListener(this);
        mSurfaceView = new CameraPreview(this);
        mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                CameraInterface.getInstance().focusOnTouch((int) event.getX(), (int) event.getY(), flCamera);
                return false;
            }
        });
        flCamera.addView(mSurfaceView);
    }

    /**
     * 压缩照片
     *
     * @param pictureFile
     */
    private void compressPhoto(File pictureFile) {
        CompressTools.Builder builder = new CompressTools.Builder(this).setDestinationDirectoryPath(FileUtil.getBasePhotoPath(this));
//        Camera.Size picSize = CameraInterface.getInstance().getPicSize();
//        if (picSize != null && picSize.width > 0 && picSize.height > 0) {
//            AppUtil.showLog("picSize.width：" + picSize.width + "picSize.height：" + picSize.height);
        builder.setMaxWidth(SystemUtil.getScreenWidth(this));
        builder.setMaxHeight(SystemUtil.getScreenHeight(this));
//        }
        builder.build().compressToFileJni(pictureFile, new CompressTools.OnCompressListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(File file) {
                AppUtil.showLog(file.exists() + "压缩成功：" + file);
                handlePicture(file);
            }
        });
    }

    /**
     * 裁剪照片
     *
     * @param file
     */
    private void handlePicture(File file) {
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            AppUtil.showLog(bitmap.getWidth());
            int x = Math.round((faceView.getCenterX() - faceView.getRadius()) / faceView.getWidth1() * bitmap.getWidth());
            int y = Math.round((faceView.getCenterY() - faceView.getRadius()) / faceView.getHeight1() * bitmap.getHeight());
            int width = Math.round(faceView.getRadius() * 2 / faceView.getWidth1() * bitmap.getWidth());
            int height = Math.round(faceView.getRadius() * 2 / faceView.getHeight1() * bitmap.getHeight());
            Matrix matrix = new Matrix();
            matrix.postScale(-1, 1); // 镜像水平翻转
            bitmap = Bitmap.createBitmap(bitmap, x, y, width, height, matrix, true);
            file1 = new File(FileUtil.getBaseCropPath(RegisterFace2Activity.this) + "/" + System.currentTimeMillis() + ".jpg");
            file1.createNewFile();
            BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file1));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
            if (result) {
                Intent intent = new Intent();
                intent.putExtra("file", file1);
                setResult(RESULT_OK, intent);
                finish();
            } else
                loginAndRegisterModel.faceDetection(file1);
        } catch (Exception e) {
            AppUtil.showLog("图片处理错误：" + e);
            AppUtil.showToast(this, "图片处理错误，请重试");
        } finally {
            hideProgress();
        }
    }

    /**
     * 拍照成功回调
     *
     * @param pictureFile
     */
    @Override
    public void onTakePictureSuccess(File pictureFile) {
        AppUtil.showLog("拍照成功：" + pictureFile.getAbsolutePath());
        compressPhoto(pictureFile);
    }

    /**
     * 拍照失败回调
     *
     * @param data
     */
    @Override
    public void onTakePictureFail(byte[] data) {
        hideProgress();
        AppUtil.showLog("拍照失败：" + data);
    }

    @OnClick({R2.id.iv_take_photo, R2.id.iv_close})
    public void onViewClicked(View view) {
        if (CommonUtil.isFastClick()) {
            return;
        }
        int i = view.getId();
        if (i == R.id.iv_take_photo) {
            showProgress();
            CameraInterface.getInstance().takePicture();
        } else if (i == R.id.iv_close) {
            finish();
        }
    }

    @Override
    public void onFaceDetectionSuccess(BaseBean<FaceDetectionBean> data) {
        hideProgress();
        boolean ok = false;
        if (data != null) {
            if (data.getCode() == 200 && data.getData() != null) {
                List<FaceDetectionBean.FaceListBean> faceList = data.getData().getFace_list();
                if (faceList != null && faceList.size() > 0) {
                    FaceDetectionBean.FaceListBean faceBean = faceList.get(0);
                    if (faceBean != null) {
                        if (faceBean.getFace_probability() == 1) {
                            ok = true;
                        }
                    }
                }
            }
        }
        if (ok || getIntent().getBooleanExtra("jump", false))
            startActivity(new Intent()
                    .setComponent(new ComponentName(RegisterFace2Activity.this, getIntent().getStringExtra("activity")))
                    .putExtra("file", file1)
                    .putExtra("ok", ok));
        else
            ToastUtil.showTextToast(this, "照片质量不太合格，按照提示拍照哦");
    }

    @Override
    public void onFaceDetectionFailure() {
        hideProgress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (loginAndRegisterModel != null) {
            loginAndRegisterModel.removeListener();
        }
        CameraInterface.getInstance().setCameraListener(null);
    }

    @Override
    public void onAllPermissionGrant() {
        initCameraView();
    }
}
